﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Simple.Common.EasyUICommon;

namespace Simple.Web.Framework.Infrastructure.Aop
{
    public class ModelStateFilterAttribute : ActionFilterAttribute
    {
        private string GetModelErrorMsg(ModelStateDictionary ModelState)
        {
            string str = string.Empty;
            foreach (ModelState modelState in ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    if (!string.IsNullOrEmpty(error.ErrorMessage))
                    {
                        str = error.ErrorMessage; break;
                    }
                }
                if (!string.IsNullOrEmpty(str)) break;
            }

            return str;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (string.Equals(filterContext.RequestContext.HttpContext.Request.RequestType,"POST", StringComparison.CurrentCultureIgnoreCase) && !filterContext.Controller.ViewData.ModelState.IsValid)
            {
                string errorString = GetModelErrorMsg(filterContext.Controller.ViewData.ModelState);
                filterContext.Result = new JsonResult()
                {
                    Data = SimpleResult.GetError(errorString),
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
        }

    }
}